<template>
  <div class="course-management">
    <div class="header">
      <h2>课程管理</h2>
      <div class="actions">
        <button class="btn btn-primary" @click="showCreateModal = true">
          <i class="fas fa-plus"></i>
          添加课程
        </button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filters">
      <div class="search-box">
        <i class="fas fa-search"></i>
        <input 
          v-model="searchQuery" 
          type="text" 
          placeholder="搜索课程名称或课程代码"
          @input="handleSearch"
        >
      </div>
      <select v-model="statusFilter" @change="loadCourses">
        <option value="">全部状态</option>
        <option value="active">启用</option>
        <option value="inactive">禁用</option>
      </select>
      <select v-model="categoryFilter" @change="loadCourses">
        <option value="">全部分类</option>
        <option value="required">必修课</option>
        <option value="elective">选修课</option>
        <option value="practical">实践课</option>
      </select>
    </div>

    <!-- 课程列表 -->
    <div class="table-container">
      <table class="courses-table">
        <thead>
          <tr>
            <th>
              <input 
                type="checkbox" 
                :checked="isAllSelected" 
                @change="toggleSelectAll"
              >
            </th>
            <th>课程代码</th>
            <th>课程名称</th>
            <th>学分</th>
            <th>课程类型</th>
            <th>授课教师</th>
            <th>状态</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="course in courses" :key="course.id">
            <td>
              <input 
                type="checkbox" 
                :value="course.id" 
                v-model="selectedCourses"
              >
            </td>
            <td>{{ course.course_code }}</td>
            <td>
              <div class="course-info">
                <div class="course-name">{{ course.name }}</div>
                <div class="course-desc">{{ course.description || '-' }}</div>
              </div>
            </td>
            <td>{{ course.credits }}</td>
            <td>
              <span :class="['category', course.category]">
                {{ getCategoryLabel(course.category) }}
              </span>
            </td>
            <td>
              <div class="teachers-list">
                <span 
                  v-for="teacher in course.teachers" 
                  :key="teacher.id"
                  class="teacher-tag"
                >
                  {{ teacher.name }}
                </span>
                <span v-if="!course.teachers || course.teachers.length === 0" class="no-teacher">
                  未分配
                </span>
              </div>
            </td>
            <td>
              <span :class="['status', course.status]">
                {{ course.status === 'active' ? '启用' : '禁用' }}
              </span>
            </td>
            <td>{{ formatDate(course.created_at) }}</td>
            <td>
              <div class="actions">
                <button 
                  class="btn btn-sm btn-outline" 
                  @click="editCourse(course)"
                >
                  编辑
                </button>
                <button 
                  class="btn btn-sm btn-outline" 
                  @click="manageTeachers(course)"
                >
                  分配教师
                </button>
                <button 
                  :class="['btn', 'btn-sm', course.status === 'active' ? 'btn-warning' : 'btn-success']"
                  @click="toggleStatus(course)"
                >
                  {{ course.status === 'active' ? '禁用' : '启用' }}
                </button>
                <button 
                  class="btn btn-sm btn-danger" 
                  @click="deleteCourse(course)"
                >
                  删除
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <button 
        :disabled="currentPage === 1" 
        @click="changePage(currentPage - 1)"
      >
        上一页
      </button>
      <span>第 {{ currentPage }} 页，共 {{ totalPages }} 页</span>
      <button 
        :disabled="currentPage === totalPages" 
        @click="changePage(currentPage + 1)"
      >
        下一页
      </button>
    </div>

    <!-- 批量操作 -->
    <div v-if="selectedCourses.length > 0" class="batch-actions">
      <span>已选择 {{ selectedCourses.length }} 个课程</span>
      <button class="btn btn-danger" @click="batchDelete">
        批量删除
      </button>
    </div>

    <!-- 创建/编辑课程模态框 -->
    <div v-if="showCreateModal || showEditModal" class="modal-overlay" @click="closeModals">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>{{ showCreateModal ? '添加课程' : '编辑课程' }}</h3>
          <button class="close-btn" @click="closeModals">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveCourse">
            <div class="form-row">
              <div class="form-group">
                <label>课程代码 *</label>
                <input 
                  v-model="courseForm.course_code" 
                  type="text" 
                  required
                  :disabled="showEditModal"
                  placeholder="如：CS101"
                >
              </div>
              <div class="form-group">
                <label>课程名称 *</label>
                <input 
                  v-model="courseForm.name" 
                  type="text" 
                  required
                  placeholder="如：计算机科学导论"
                >
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>学分 *</label>
                <input 
                  v-model.number="courseForm.credits" 
                  type="number" 
                  min="1" 
                  max="10" 
                  required
                >
              </div>
              <div class="form-group">
                <label>课程类型 *</label>
                <select v-model="courseForm.category" required>
                  <option value="">请选择类型</option>
                  <option value="required">必修课</option>
                  <option value="elective">选修课</option>
                  <option value="practical">实践课</option>
                </select>
              </div>
            </div>
            <div class="form-group">
              <label>课程描述</label>
              <textarea 
                v-model="courseForm.description" 
                rows="3"
                placeholder="请输入课程描述"
              ></textarea>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>学期</label>
                <input 
                  v-model="courseForm.semester" 
                  type="text"
                  placeholder="如：2024春季"
                >
              </div>
              <div class="form-group">
                <label>课时</label>
                <input 
                  v-model.number="courseForm.hours" 
                  type="number"
                  min="1"
                  placeholder="总课时数"
                >
              </div>
            </div>
            <div class="form-actions">
              <button type="button" class="btn btn-outline" @click="closeModals">
                取消
              </button>
              <button type="submit" class="btn btn-primary">
                {{ showCreateModal ? '创建' : '保存' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 分配教师模态框 -->
    <div v-if="showTeacherModal" class="modal-overlay" @click="closeModals">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>分配教师 - {{ currentCourse?.name }}</h3>
          <button class="close-btn" @click="closeModals">&times;</button>
        </div>
        <div class="modal-body">
          <div class="teacher-assignment">
            <div class="available-teachers">
              <h4>可分配教师</h4>
              <div class="search-box">
                <i class="fas fa-search"></i>
                <input 
                  v-model="teacherSearchQuery" 
                  type="text" 
                  placeholder="搜索教师"
                  @input="searchTeachers"
                >
              </div>
              <div class="teacher-list">
                <div 
                  v-for="teacher in availableTeachers" 
                  :key="teacher.id"
                  class="teacher-item"
                  @click="assignTeacher(teacher)"
                >
                  <div class="teacher-info">
                    <div class="teacher-name">{{ teacher.name }}</div>
                    <div class="teacher-details">{{ teacher.employee_id }} - {{ teacher.email }}</div>
                  </div>
                  <button class="btn btn-sm btn-primary">
                    <i class="fas fa-plus"></i>
                  </button>
                </div>
              </div>
            </div>
            
            <div class="assigned-teachers">
              <h4>已分配教师</h4>
              <div class="teacher-list">
                <div 
                  v-for="teacher in assignedTeachers" 
                  :key="teacher.id"
                  class="teacher-item assigned"
                >
                  <div class="teacher-info">
                    <div class="teacher-name">{{ teacher.name }}</div>
                    <div class="teacher-details">{{ teacher.employee_id }} - {{ teacher.email }}</div>
                  </div>
                  <button 
                    class="btn btn-sm btn-danger"
                    @click="removeTeacher(teacher)"
                  >
                    <i class="fas fa-times"></i>
                  </button>
                </div>
              </div>
            </div>
          </div>
          <div class="form-actions">
            <button type="button" class="btn btn-outline" @click="closeModals">
              关闭
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { 
  getCourses, 
  createCourse, 
  updateCourse, 
  deleteCourse,
  getCourseTeachers,
  assignTeacherToCourse,
  removeTeacherFromCourse
} from '@/api/rbac'
import { getTeachers } from '@/api/rbac'

export default {
  name: 'CourseManagement',
  setup() {
    const courses = ref([])
    const loading = ref(false)
    const searchQuery = ref('')
    const statusFilter = ref('')
    const categoryFilter = ref('')
    const selectedCourses = ref([])
    const currentPage = ref(1)
    const totalPages = ref(1)
    const pageSize = 10

    // 模态框状态
    const showCreateModal = ref(false)
    const showEditModal = ref(false)
    const showTeacherModal = ref(false)
    const currentCourse = ref(null)

    // 教师相关
    const availableTeachers = ref([])
    const assignedTeachers = ref([])
    const teacherSearchQuery = ref('')

    // 表单数据
    const courseForm = reactive({
      course_code: '',
      name: '',
      description: '',
      credits: 1,
      category: '',
      semester: '',
      hours: null
    })

    // 计算属性
    const isAllSelected = computed(() => {
      return courses.value.length > 0 && selectedCourses.value.length === courses.value.length
    })

    // 方法
    const loadCourses = async () => {
      loading.value = true
      try {
        const params = {
          page: currentPage.value,
          pageSize: pageSize,
          search: searchQuery.value,
          status: statusFilter.value,
          category: categoryFilter.value
        }
        const response = await getCourses(params)
        courses.value = response.data.data
        totalPages.value = Math.ceil(response.data.total / pageSize)
      } catch (error) {
        console.error('加载课程列表失败:', error)
      } finally {
        loading.value = false
      }
    }

    const handleSearch = () => {
      currentPage.value = 1
      loadCourses()
    }

    const changePage = (page) => {
      currentPage.value = page
      loadCourses()
    }

    const toggleSelectAll = () => {
      if (isAllSelected.value) {
        selectedCourses.value = []
      } else {
        selectedCourses.value = courses.value.map(c => c.id)
      }
    }

    const getCategoryLabel = (category) => {
      const labels = {
        required: '必修课',
        elective: '选修课',
        practical: '实践课'
      }
      return labels[category] || category
    }

    const editCourse = (course) => {
      currentCourse.value = course
      Object.assign(courseForm, {
        course_code: course.course_code,
        name: course.name,
        description: course.description,
        credits: course.credits,
        category: course.category,
        semester: course.semester,
        hours: course.hours
      })
      showEditModal.value = true
    }

    const saveCourse = async () => {
      try {
        if (showCreateModal.value) {
          await createCourse(courseForm)
        } else {
          await updateCourse(currentCourse.value.id, courseForm)
        }
        closeModals()
        loadCourses()
      } catch (error) {
        console.error('保存课程失败:', error)
      }
    }

    const deleteCourse = async (course) => {
      if (confirm(`确定要删除课程 ${course.name} 吗？`)) {
        try {
          await deleteCourse(course.id)
          loadCourses()
        } catch (error) {
          console.error('删除课程失败:', error)
        }
      }
    }

    const batchDelete = async () => {
      if (confirm(`确定要删除选中的 ${selectedCourses.value.length} 个课程吗？`)) {
        try {
          // 这里需要实现批量删除API
          for (const courseId of selectedCourses.value) {
            await deleteCourse(courseId)
          }
          selectedCourses.value = []
          loadCourses()
        } catch (error) {
          console.error('批量删除失败:', error)
        }
      }
    }

    const toggleStatus = async (course) => {
      const newStatus = course.status === 'active' ? 'inactive' : 'active'
      try {
        await updateCourse(course.id, { status: newStatus })
        loadCourses()
      } catch (error) {
        console.error('切换状态失败:', error)
      }
    }

    const manageTeachers = async (course) => {
      currentCourse.value = course
      try {
        // 加载已分配的教师
        const assignedResponse = await getCourseTeachers(course.id)
        assignedTeachers.value = assignedResponse.data.teachers || []
        
        // 加载所有教师
        await loadAvailableTeachers()
        
        showTeacherModal.value = true
      } catch (error) {
        console.error('加载教师信息失败:', error)
      }
    }

    const loadAvailableTeachers = async () => {
      try {
        const response = await getTeachers({ 
          search: teacherSearchQuery.value,
          status: 'active',
          pageSize: 100 
        })
        // 过滤掉已分配的教师
        const assignedIds = assignedTeachers.value.map(t => t.id)
        availableTeachers.value = response.data.data.filter(t => !assignedIds.includes(t.id))
      } catch (error) {
        console.error('加载可用教师失败:', error)
      }
    }

    const searchTeachers = () => {
      loadAvailableTeachers()
    }

    const assignTeacher = async (teacher) => {
      try {
        await assignTeacherToCourse(currentCourse.value.id, teacher.id)
        // 移动教师到已分配列表
        assignedTeachers.value.push(teacher)
        availableTeachers.value = availableTeachers.value.filter(t => t.id !== teacher.id)
      } catch (error) {
        console.error('分配教师失败:', error)
      }
    }

    const removeTeacher = async (teacher) => {
      try {
        await removeTeacherFromCourse(currentCourse.value.id, teacher.id)
        // 移动教师到可分配列表
        availableTeachers.value.push(teacher)
        assignedTeachers.value = assignedTeachers.value.filter(t => t.id !== teacher.id)
      } catch (error) {
        console.error('移除教师失败:', error)
      }
    }

    const closeModals = () => {
      showCreateModal.value = false
      showEditModal.value = false
      showTeacherModal.value = false
      currentCourse.value = null
      teacherSearchQuery.value = ''
      Object.assign(courseForm, {
        course_code: '',
        name: '',
        description: '',
        credits: 1,
        category: '',
        semester: '',
        hours: null
      })
    }

    const formatDate = (dateString) => {
      return new Date(dateString).toLocaleDateString('zh-CN')
    }

    onMounted(() => {
      loadCourses()
    })

    return {
      courses,
      loading,
      searchQuery,
      statusFilter,
      categoryFilter,
      selectedCourses,
      currentPage,
      totalPages,
      showCreateModal,
      showEditModal,
      showTeacherModal,
      currentCourse,
      availableTeachers,
      assignedTeachers,
      teacherSearchQuery,
      courseForm,
      isAllSelected,
      loadCourses,
      handleSearch,
      changePage,
      toggleSelectAll,
      getCategoryLabel,
      editCourse,
      saveCourse,
      deleteCourse,
      batchDelete,
      toggleStatus,
      manageTeachers,
      searchTeachers,
      assignTeacher,
      removeTeacher,
      closeModals,
      formatDate
    }
  }
}
</script>

<style scoped>
.course-management {
  padding: 0;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header h2 {
  margin: 0;
  color: #1f2937;
}

.filters {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  align-items: center;
  flex-wrap: wrap;
}

.search-box {
  position: relative;
  flex: 1;
  max-width: 400px;
}

.search-box i {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #6b7280;
}

.search-box input {
  width: 100%;
  padding: 8px 12px 8px 36px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
}

.filters select {
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
}

.table-container {
  overflow-x: auto;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
}

.courses-table {
  width: 100%;
  border-collapse: collapse;
  min-width: 1000px;
}

.courses-table th,
.courses-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #e5e7eb;
}

.courses-table th {
  background: #f9fafb;
  font-weight: 600;
  color: #374151;
}

.course-info {
  min-width: 200px;
}

.course-name {
  font-weight: 500;
  color: #1f2937;
  margin-bottom: 4px;
}

.course-desc {
  font-size: 12px;
  color: #6b7280;
  line-height: 1.4;
}

.category {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.category.required {
  background: #dbeafe;
  color: #1e40af;
}

.category.elective {
  background: #d1fae5;
  color: #065f46;
}

.category.practical {
  background: #fef3c7;
  color: #92400e;
}

.teachers-list {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  max-width: 150px;
}

.teacher-tag {
  background: #f3f4f6;
  color: #374151;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 11px;
}

.no-teacher {
  color: #9ca3af;
  font-size: 12px;
  font-style: italic;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status.active {
  background: #d1fae5;
  color: #065f46;
}

.status.inactive {
  background: #fee2e2;
  color: #991b1b;
}

.actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 4px;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 11px;
}

.btn-primary {
  background: #3b82f6;
  color: white;
}

.btn-outline {
  background: transparent;
  color: #6b7280;
  border: 1px solid #d1d5db;
}

.btn-success {
  background: #10b981;
  color: white;
}

.btn-warning {
  background: #f59e0b;
  color: white;
}

.btn-danger {
  background: #ef4444;
  color: white;
}

.btn:hover {
  opacity: 0.8;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  margin-top: 24px;
}

.batch-actions {
  position: fixed;
  bottom: 24px;
  left: 50%;
  transform: translateX(-50%);
  background: white;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  gap: 16px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 800px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #e5e7eb;
}

.modal-header h3 {
  margin: 0;
  color: #1f2937;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #6b7280;
}

.modal-body {
  padding: 24px;
}

.form-row {
  display: flex;
  gap: 16px;
}

.form-group {
  flex: 1;
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 4px;
  font-weight: 500;
  color: #374151;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
}

.form-group textarea {
  resize: vertical;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

.teacher-assignment {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  margin-bottom: 24px;
}

.teacher-assignment h4 {
  margin: 0 0 12px 0;
  color: #1f2937;
}

.teacher-list {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
}

.teacher-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  border-bottom: 1px solid #e5e7eb;
  cursor: pointer;
  transition: background 0.2s;
}

.teacher-item:last-child {
  border-bottom: none;
}

.teacher-item:hover {
  background: #f9fafb;
}

.teacher-item.assigned {
  background: #f0f9ff;
}

.teacher-info {
  flex: 1;
}

.teacher-name {
  font-weight: 500;
  color: #1f2937;
  margin-bottom: 2px;
}

.teacher-details {
  font-size: 12px;
  color: #6b7280;
}

@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
  }
  
  .filters {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-box {
    max-width: none;
  }
  
  .teacher-assignment {
    grid-template-columns: 1fr;
  }
}
</style>